﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Peak.ApplicationServices.Services;
using Peak.Core;
using Peak.Core.DataInterfaces;
using Peak.Web.Controllers.Models;
using Peak.Web.Controllers.Services;
using SharpArch.Web.NHibernate;
using MvcContrib;

namespace Peak.Web.Controllers
{
  public class SelectStoriesController : BaseController
  {
    public class StoryEqualityComparer : IEqualityComparer<Story>
    {
      public bool Equals(Story x, Story y)
      {
        return x.Id == y.Id;
      }

      public int GetHashCode(Story obj)
      {
        return obj.Id.GetHashCode();
      }
    }
    private readonly IStoryRepository _storyService;
    private readonly ISprintService _sprintService;

    public SelectStoriesController(ISessionService sessionService, IStoryRepository storyService, ISprintService sprintService)
      :base(sessionService)
    {
      _storyService = storyService;
      _sprintService = sprintService;
    }

    public ActionResult Index(int? sprintId, string returnUrl, bool multipleSelection,StoryFilterModel storyFilterModel)
    {
      StoryFilter sf = new StoryFilter();
      storyFilterModel.Update(sf, _sessionService.Project.Id);
      Page<Story> stories = _storyService.GetPage(sf);
      List<Story> list;
      if(sprintId != null)
      {
        Sprint sprint = _sprintService.Get(sprintId.Value);
        list = stories.Results.Except(sprint.SprintStories.Select(f => f.Story), new StoryEqualityComparer()).ToList();
      }
      else
      {
        list = stories.Results.ToList();
      }

      return View(new SelectStoriesModel(sprintId, list ,returnUrl.Replace("\"",""), multipleSelection));
    }        
  }
}
